


var os = null
var fs = null
try {
    os = require("os")
    fs = require("fs")
} catch(e){}

function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function str2ab(str) {
    var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}
//---------------------------------------------
//var variconv = require('iconv-lite');
var convertStringToArrayBuffer = function (str) {
    var buf = new ArrayBuffer(str.length);
    var bufView = new Uint8Array(buf);
    for (var i = 0; i < str.length; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}
function _com_owc(data, delay) {
    if (!chrome || !chrome.serial) {
        console.log("当前环境不支持chrome.serial api")
        return
    }
    chrome.serial.connect(_app.cur_serial, _app.serial_config, function (conn) {
        if (!conn) {
            alert("打开串口失败!!!")
            return
        }
        _app.syslog("串口发送:" + data)
        var cmdline = str2ab(data + "\r\n")
        chrome.serial.send(conn.connectionId, cmdline, function (re) {
            if (re.error) {
                _app.syslog("写串口" + re.error)
                //alert("写串口失败!!! " + re.error);
                return
            }
            setTimeout(function () {
                // 读取完就关闭
                chrome.serial.disconnect(conn.connectionId, function (result) {
                    console.log("serial disconnect = " + result)
                    _app.syslog("关闭串口" + result)
                })
            }, 2000)
        })
    })
}
var _app = new Vue({
    el: '#app',
    data: {
        visible: false,
        cur_serial: "COM1",
        serials: [], // 可用串口
        dtu_config: default_conf, // 初始化为默认配置
        serial_config: {
            bitrate: 115200,
            dataBits: "eight",
            parityBit: "no",
            stopBits: "one",
            receiveTimeout: 0,
            sendTimeout: 2000
        },
        sys_log: {
            visible: true,
            data: ""
        },
        devinfo: {
            imei: "",
            iccid: "",
            ver: "",
            project: "",
            vbatt: "",
            csq: "",
            location: ""
        },
        cur_menu_tab: "basic",
        cur_uart_tab: "uart1",
        cur_net_tab: "net1",
        com_cmds: [],
        has_chrome_serial : (chrome && chrome.serial)
    },
    methods: {
        reload_serial_list: function () {
            _getDevices()
        },
        read_dtu_config: function () {
            _com_owc("config,readconfig", 2000)
        },
        write_dtu_config: function () {
            var jdata = JSON.stringify(_app.dtu_config)
            _com_owc("config,writeconfig," + jdata, 2000)
            if (fs)
                fs.writeFile("last_dtu_config.json", jdata, function () { })
        },
        export_dtu_config: function () {
            alert("还没做好呀")
        },
        import_dtu_config: function () {
            alert("还没做好呀")
        },
        syslog: function (line) {
            _app.sys_log.data = line + "\r\n" + _app.sys_log.data
        },
        read_devinfo: function () {
            if (!chrome || !chrome.serial) {
                console.log("当前环境不支持chrome.serial api")
                return
            }
            chrome.serial.connect(_app.cur_serial, _app.serial_config, function (conn) {
                if (!conn) {
                    alert("打开串口失败!!!")
                    return
                }
                _app.com_cmds = ["rrpc,geticcid", "rrpc,getcsq", "rrpc,getver", "rrpc,getproject", "rrpc,getvbatt"]
                chrome.serial.send(conn.connectionId, str2ab("rrpc,getimei\r\n"), function (re) { })
            })
        },
        rrpc: function (cmd, args) {
            var cmdline = "rrpc," + cmd
            _com_owc(cmdline, 2000)
        },
        change_menu: function () { },
        copy_dtu_config_to_clipboard: function () {
            var jdata = JSON.stringify(_app.dtu_config)
            navigator.clipboard.writeText(jdata)
                .then(() => {
                    alert("已复制")
                })
                .catch(err => {
                    alert('失败了 ' + err)
                });
        }
    }
})
function _getDevices() {
    if (!chrome || !chrome.serial) {
        console.log("当前环境不支持chrome.serial api")
        return
    }

    chrome.serial.getDevices(function (serials) {
        var tmp = []
        for (j = 0; j < serials.length; j++) {
            var se = serials[j]
            if (os.platform == "win32") {
                if (se.path && se.path.indexOf("COM") > 0) {
                    se.nickName = se.path.substring(se.path.indexOf("COM")) + "-" + se.displayName
                }
                else {
                    se.nickName = se.path + "-" + se.displayName
                }
            }
            else {
                se.nickName = se.path + "-" + se.displayName
            }
            tmp.push(se)
        }
        tmp.sort(function (prev, next) {
            if (prev.nickName > next.nickName)
                return 1
            else if (prev.nickName < next.nickName)
                return -1
            else
                return 0
        })
        _app.serials = tmp
    })
}
_getDevices()
function fix_dtu_config(dtu_config) {
    // 修正串口配置
    if (!dtu_config.uconf) {
        dtu_config.uconf = [[1, "115200", 8, 2, 0, ""], [2, "115200", 8, 2, 0, ""]]
    }
    if (!Array.isArray(dtu_config.uconf)) {
        dtu_config.uconf = [[1, "115200", 8, 2, 0, ""], [2, "115200", 8, 2, 0, ""]]
    }
    if (dtu_config.uconf.length == 1) {
        if (dtu_config.uconf[0][0] == 1) {
            dtu_config.uconf.push([2, "115200", 8, 2, 0, ""])
        }
        else {
            dtu_config.uconf.unshift([2, "115200", 8, 2, 0, ""])
        }
    }
    // 修正网络配置
    if (!dtu_config.conf) {
        dtu_config.conf = []
    }
    if (dtu_config.conf.length < 7) {
        for (var i = 0; i < 7 - dtu_config.conf.length; i++)
            dtu_config.conf.push([])
    }
    for (var i = 0; i < dtu_config.conf.length; i++) {
        var _conf = dtu_config.conf[i]
        if (!Array.isArray(_conf)) {
            dtu_config.conf[i] = ["", {}]
        }
    }
    return dtu_config
}
var com_datas = ""
if (!chrome || !chrome.serial) {
    console.log("当前环境不支持chrome.serial api")
}
else {
    chrome.serial.onReceive.addListener(function (ent) {
        console.log(ent)
        if (ent.data) {
            var resp = com_datas + ab2str(ent.data)
            if (!resp.endsWith("\r\n")) {
                com_datas = resp
                return
            }
            resp = resp.trim()
            com_datas = ""
            _app.syslog("串口接收: " + resp)
            if (resp == "OK" || resp == "ERROR") {
                _app.syslog("命令执行结果: " + resp)
            }
            else if (resp.startsWith("{") && resp.endsWith("}")) {
                _app.dtu_config = fix_dtu_config(JSON.parse(resp))
                alert("读取DTU配置成功")
            }
            else if (resp.startsWith("rrpc,")) {
                var tmp = resp.split(",")
                switch (tmp[1]) {
                    case "getimei": {
                        _app.devinfo.imei = tmp[2]
                        break
                    }
                    case "geticcid": {
                        _app.devinfo.iccid = tmp[2]
                        break
                    }
                    case "getcsq": {
                        _app.devinfo.csq = tmp[2]
                        break
                    }
                    case "getlocation": {
                        _app.devinfo.location = tmp[2]
                        break
                    }
                    case "getver": {
                        _app.devinfo.ver = tmp[2]
                        break
                    }
                    case "getproject": {
                        _app.devinfo.project = tmp[2]
                        break
                    }
                    case "getvbatt": {
                        _app.devinfo.vbatt = tmp[2]
                        break
                    }
                }
                var cmd = _app.com_cmds.shift()
                if (cmd) {
                    console.log("send next cmd = " + cmd)
                    chrome.serial.send(ent.connectionId, convertStringToArrayBuffer(cmd + "\r\n"), function (re) { })
                }
                else {
                    console.log("all cmd sended, close com")
                    setTimeout(function () {
                        // 读取完就关闭
                        chrome.serial.disconnect(ent.connectionId, function (result) {
                            console.log("serial disconnect = " + result)
                            _app.syslog("关闭串口" + result)
                        })
                    }, 1000)
                }
            }
        }
    })
    chrome.serial.onReceiveError.addListener(function (ent) {
        console.log(ent)
    })
}